import {
  Controller,
  Get,
  HttpException,
  HttpStatus,
  Query,
} from '@nestjs/common';
import { CategoryService } from './category.service';
import { ApiTags, ApiOperation, ApiQuery } from '@nestjs/swagger';
import { CategoryPathQueryDto } from './dto/category-path-query.dto';

@ApiTags('分类管理')
@Controller('categories')
export class CategoryController {
  constructor(private readonly categoryService: CategoryService) {}

  // 统一的分类获取接口
  @Get()
  @ApiOperation({ summary: '获取分类列表' })
  @ApiQuery({ name: 'parentId', required: false, description: '父级分类ID' })
  @ApiQuery({
    name: 'parentLevel',
    required: false,
    description: '父级分类级别(1-6)',
  })
  async getCategories(
    @Query('parentId') parentId?: string,
    @Query('parentLevel') parentLevel?: string,
  ) {
    try {
      if (!parentLevel) {
        return this.categoryService.getLevel1Categories();
      }

      const levelNum = Number(parentLevel);
      if (isNaN(levelNum) || levelNum < 1 || levelNum > 6) {
        throw new HttpException(
          { message: '分类级别必须是1-6之间的数字', code: 'INVALID_LEVEL' },
          HttpStatus.BAD_REQUEST,
        );
      }

      if (!parentId) {
        throw new HttpException(
          { message: '需要提供父级分类ID', code: 'PARENT_ID_REQUIRED' },
          HttpStatus.BAD_REQUEST,
        );
      }

      try {
        const parentIdBigInt = BigInt(parentId);
        return this.categoryService.getChildCategories(
          parentIdBigInt,
          levelNum,
        );
      } catch (e) {
        throw new HttpException(
          { message: '父级分类ID格式错误', code: 'INVALID_PARENT_ID' },
          HttpStatus.BAD_REQUEST,
        );
      }
    } catch (error) {
      if (error instanceof HttpException) {
        throw error;
      }
      throw new HttpException(
        { message: error.message, code: 'GET_CATEGORIES_ERROR' },
        HttpStatus.INTERNAL_SERVER_ERROR,
      );
    }
  }

  @Get('path')
  @ApiOperation({ summary: '获取分类路径' })
  async getCategoryPath(@Query() query: CategoryPathQueryDto) {
    try {
      const params = {
        level1Id: query.level1Id ? BigInt(query.level1Id) : undefined,
        level2Id: query.level2Id ? BigInt(query.level2Id) : undefined,
        level3Id: query.level3Id ? BigInt(query.level3Id) : undefined,
        level4Id: query.level4Id ? BigInt(query.level4Id) : undefined,
        level5Id: query.level5Id ? BigInt(query.level5Id) : undefined,
        level6Id: query.level6Id ? BigInt(query.level6Id) : undefined,
      };

      return await this.categoryService.getCategoryPath(params);
    } catch (error) {
      if (error instanceof HttpException) {
        throw error;
      }
      throw new HttpException(
        { message: error.message, code: 'GET_CATEGORY_PATH_ERROR' },
        HttpStatus.INTERNAL_SERVER_ERROR,
      );
    }
  }
}
